package com.hongkuncheng.cms.controller.frontpage;

import java.util.List;
import java.util.ArrayList;

import org.hibernate.Criteria;
import org.hibernate.sql.JoinType;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.model.Article;
import com.hongkuncheng.cms.model.ArticleReColumns;
import com.hongkuncheng.cms.model.DataitemReDepartment;
import com.hongkuncheng.cms.model.Department;
import com.hongkuncheng.cms.model.Homepage;
import com.hongkuncheng.cms.model.Leavemessage;
import com.hongkuncheng.cms.model.Zhuanti;
import com.hongkuncheng.cms.model.Columns;
import com.hongkuncheng.cms.model.Dataitem;
import com.hongkuncheng.cms.model.DataitemReColumns;
import com.hongkuncheng.cms.model.Datasortfield;
import com.hongkuncheng.cms.model.Datasortmethod;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Transactional
@RequestMapping("frontpage")
public class FindexController extends BaseController {

    // 主页频道
    @RequestMapping("homepage")
    public String homepage() {
        int homepageId = request.getParameter("homepageid") == null ? 1 :
                Integer.parseInt(request.getParameter("homepageid"));
        Homepage homepage = factorySession.get(Homepage.class, homepageId);
        request.setAttribute("homepage", homepage);
        String pagename = homepage.getTemplate();
        List<Dataitem> dataitems = factorySession.createCriteria(Dataitem.class)
                .add(Restrictions.eq("datamodel.id", homepage.getDatamodel().getId()))
                .list();
        for (Dataitem dataitem : dataitems) {
            Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                    .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("article_admin.department", "article_admin_department",
                            JoinType.LEFT_OUTER_JOIN);
            criteriaArticle.add(Restrictions.eq("articleState.id", 4));
            List<Integer> departmentIds = new ArrayList<Integer>();
            for (DataitemReDepartment drd : dataitem.getDataitemReDepartments())
                departmentIds.add(drd.getDepartment().getId());
            if (departmentIds.size() > 0) criteriaArticle
                    .add(Restrictions.in("article_admin_department.id", departmentIds));
            List<Integer> articleIds = new ArrayList<Integer>();
            articleIds.add(0);
            for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                for (ArticleReColumns arc : drc.getColumns().getArticleReColumnses())
                    if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                List<Columns> childs = factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("parentId", drc.getColumns().getId()))
                        .list();
                for (Columns child : childs) {
                    for (ArticleReColumns arc : child.getArticleReColumnses())
                        if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                }
            }
            criteriaArticle.add(Restrictions.in("id", articleIds));
            if (dataitem.getDateastrict() > 0)
                criteriaArticle.add(Restrictions.sqlRestriction("datediff(now(),publishtime)<?",
                        dataitem.getDateastrict(), StandardBasicTypes.INTEGER));
            if (dataitem.isHaveimage()) criteriaArticle.add(Restrictions.isNotNull("image"));
            Datasortfield datasortfield1 = dataitem.getDatasortfield1();
            Datasortfield datasortfield2 = dataitem.getDatasortfield2();
            Datasortfield datasortfield3 = dataitem.getDatasortfield3();
            Datasortmethod datasortmethod1 = dataitem.getDatasortmethod1();
            Datasortmethod datasortmethod2 = dataitem.getDatasortmethod2();
            Datasortmethod datasortmethod3 = dataitem.getDatasortmethod3();
            criteriaArticle.addOrder(datasortmethod1.equals("asc") ?
                    Order.asc(datasortfield1.getField()) : Order.desc(datasortfield1.getField()))
                    .addOrder(datasortmethod2.equals("asc") ?
                            Order.asc(datasortfield2.getField()) : Order.desc(datasortfield2.getField()))
                    .addOrder(datasortmethod3.equals("asc") ? Order.asc(datasortfield3.getField()) :
                            Order.desc(datasortfield3.getField()));
            int datacount = dataitem.getDatacount();
            if (datacount > 1) {
                List<Article> articles = criteriaArticle.setMaxResults(datacount).list();
                request.setAttribute(dataitem.getDataname(), articles);
            } else {
                Article article = (Article) criteriaArticle.setMaxResults(datacount).uniqueResult();
                request.setAttribute(dataitem.getDataname(), article);
            }
        }
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

    // 栏目页面
    @RequestMapping("columns")
    public String columns() {
        int columnsId = Integer.parseInt(request.getParameter("columnsid"));
        int departmentId = request.getParameter("departmentid") == null ? 0 :
                Integer.parseInt(request.getParameter("departmentid"));
        int articleId = request.getParameter("articleid") == null ? 0 :
                Integer.parseInt(request.getParameter("articleid"));
        int pageIndex = request.getParameter("pageindex") == null ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        Columns columns = factorySession.get(Columns.class, columnsId);
        request.setAttribute("columns", columns);
        String pagename = columns.getTemplatelist();
        for (Dataitem dataitem : columns.getDatamodel().getDataitems()) {
            Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                    .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("article_admin.department",
                            "article_admin_department", JoinType.LEFT_OUTER_JOIN);
            criteriaArticle.add(Restrictions.eq("articleState.id", 4));
            if (departmentId == 0) {
                // 部门筛选
                List<Integer> departmentIds = new ArrayList<Integer>();
                for (DataitemReDepartment drd : dataitem.getDataitemReDepartments())
                    departmentIds.add(drd.getDepartment().getId());
                if (departmentIds.size() > 0) criteriaArticle
                        .add(Restrictions.in("article_admin_department.id", departmentIds));
            } else {
                // 部门分组
                criteriaArticle.add(Restrictions.eq("article_admin_department.id", departmentId));
            }
            List<Integer> articleIds = new ArrayList<Integer>();
            articleIds.add(0);
            if (!dataitem.isPagesign() || articleId == 0) {
                if (dataitem.isDynamiccolumns()) {
                    // 动态栏目
                    for (ArticleReColumns arc : columns.getArticleReColumnses())
                        if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                    List<Columns> childs = factorySession.createCriteria(Columns.class)
                            .add(Restrictions.eq("parentId", columns.getId()))
                            .list();
                    for (Columns child : childs) {
                        for (ArticleReColumns arc : child.getArticleReColumnses())
                            if (!articleIds.contains(arc.getArticle().getId()))
                                articleIds.add(arc.getArticle().getId());
                    }
                } else {
                    // 静态栏目
                    for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                        for (ArticleReColumns arc : drc.getColumns().getArticleReColumnses())
                            if (!articleIds.contains(arc.getArticle().getId()))
                                articleIds.add(arc.getArticle().getId());
                        List<Columns> childs = factorySession.createCriteria(Columns.class)
                                .add(Restrictions.eq("parentId", drc.getColumns().getId()))
                                .list();
                        for (Columns child : childs) {
                            for (ArticleReColumns arc : child.getArticleReColumnses())
                                if (!articleIds.contains(arc.getArticle().getId()))
                                    articleIds.add(arc.getArticle().getId());
                        }
                    }
                }

            } else {
                articleIds.add(articleId);
            }
            criteriaArticle.add(Restrictions.in("id", articleIds));
            if (!dataitem.isPagesign() || articleId == 0) {
                if (dataitem.getDateastrict() > 0) criteriaArticle
                        .add(Restrictions.sqlRestriction("datediff(now(),publishtime)<?",
                                dataitem.getDateastrict(), StandardBasicTypes.INTEGER));
                if (dataitem.isHaveimage()) criteriaArticle.add(Restrictions.isNotNull("image"));
                Datasortfield datasortfield1 = dataitem.getDatasortfield1();
                Datasortfield datasortfield2 = dataitem.getDatasortfield2();
                Datasortfield datasortfield3 = dataitem.getDatasortfield3();
                Datasortmethod datasortmethod1 = dataitem.getDatasortmethod1();
                Datasortmethod datasortmethod2 = dataitem.getDatasortmethod2();
                Datasortmethod datasortmethod3 = dataitem.getDatasortmethod3();
                criteriaArticle.addOrder(datasortmethod1.equals("asc") ? Order.asc(datasortfield1.getField()) :
                        Order.desc(datasortfield1.getField())).addOrder(datasortmethod2.equals("asc") ?
                        Order.asc(datasortfield2.getField()) :
                        Order.desc(datasortfield2.getField())).addOrder(datasortmethod3.equals("asc") ?
                        Order.asc(datasortfield3.getField()) :
                        Order.desc(datasortfield3.getField()));
            }
            int datacount = dataitem.getDatacount();
            if (datacount > 1) {
                List<Article> articles = null;
                if (dataitem.isPagesign()) {
                    articles = criteriaArticle.setFirstResult((pageIndex - 1) * datacount)
                            .setMaxResults(datacount).list();
                    int recordcount = articles.size() == 0 ? 0 :
                            Integer.parseInt(criteriaArticle.setProjection(Projections.countDistinct("id"))
                                    .setFirstResult(0).uniqueResult().toString());
                    if ((columns.isAutosingle() || articleId > 0) && recordcount == 1) {
                        // 如果当前栏目支持自动单页列表只有一篇文章，则使用其对应详细模板
                        pagename = columns.getTemplatedetail();
                    } else {
                        int pagecount = DataHelper.calcPageCount(recordcount, datacount);
                        if (pagecount > 10) pagecount = 10;
                        request.setAttribute("pagecount", pagecount);
                        request.setAttribute("pageindex", pageIndex);
                        if (recordcount > pagecount * datacount) {
                            recordcount = pagecount * datacount;
                        }
                        request.setAttribute("recordcount", recordcount);
                    }
                } else {
                    articles = criteriaArticle.setMaxResults(datacount).list();
                }
                request.setAttribute(dataitem.getDataname(), articles);
            } else {
                Article article = (Article) criteriaArticle.setMaxResults(datacount).uniqueResult();
                request.setAttribute(dataitem.getDataname(), article);
            }
        }
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

    // 专题频道
    @RequestMapping("zhuanti")
    public String zhuanti() {
        int zhuantiId = Integer.parseInt(request.getParameter("zhuantiid"));
        Zhuanti zhuanti = factorySession.get(Zhuanti.class, zhuantiId);
        request.setAttribute("zhuanti", zhuanti);
        String pagename = zhuanti.getTemplate();
        List<Dataitem> dataitems = factorySession.createCriteria(Dataitem.class)
                .add(Restrictions.eq("datamodel.id", zhuanti.getDatamodel().getId()))
                .list();
        for (Dataitem dataitem : dataitems) {
            Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                    .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("article_admin.department",
                            "article_admin_department", JoinType.LEFT_OUTER_JOIN);
            criteriaArticle.add(Restrictions.eq("articleState.id", 4));
            List<Integer> departmentIds = new ArrayList<Integer>();
            for (DataitemReDepartment drd : dataitem.getDataitemReDepartments())
                departmentIds.add(drd.getDepartment().getId());
            if (departmentIds.size() > 0) criteriaArticle
                    .add(Restrictions.in("article_admin_department.id", departmentIds));
            List<Integer> articleIds = new ArrayList<Integer>();
            articleIds.add(0);
            for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                for (ArticleReColumns arc : drc.getColumns().getArticleReColumnses())
                    if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                List<Columns> childs = factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("parentId", drc.getColumns().getId())).list();
                for (Columns child : childs) {
                    for (ArticleReColumns arc : child.getArticleReColumnses())
                        if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                }
            }
            criteriaArticle.add(Restrictions.in("id", articleIds));
            if (dataitem.getDateastrict() > 0) criteriaArticle
                    .add(Restrictions.sqlRestriction("datediff(now(),publishtime)<?",
                            dataitem.getDateastrict(), StandardBasicTypes.INTEGER));
            if (dataitem.isHaveimage()) criteriaArticle.add(Restrictions.isNotNull("image"));
            Datasortfield datasortfield1 = dataitem.getDatasortfield1();
            Datasortfield datasortfield2 = dataitem.getDatasortfield2();
            Datasortfield datasortfield3 = dataitem.getDatasortfield3();
            Datasortmethod datasortmethod1 = dataitem.getDatasortmethod1();
            Datasortmethod datasortmethod2 = dataitem.getDatasortmethod2();
            Datasortmethod datasortmethod3 = dataitem.getDatasortmethod3();
            criteriaArticle.addOrder(datasortmethod1.equals("asc") ? Order.asc(datasortfield1.getField()) :
                    Order.desc(datasortfield1.getField())).addOrder(datasortmethod2.equals("asc") ?
                    Order.asc(datasortfield2.getField()) :
                    Order.desc(datasortfield2.getField())).addOrder(datasortmethod3.equals("asc") ?
                    Order.asc(datasortfield3.getField()) :
                    Order.desc(datasortfield3.getField()));
            int datacount = dataitem.getDatacount();
            if (datacount > 1) {
                List<Article> articles = criteriaArticle.setMaxResults(datacount).list();
                request.setAttribute(dataitem.getDataname(), articles);
            } else {
                Article article = (Article) criteriaArticle.setMaxResults(datacount).uniqueResult();
                request.setAttribute(dataitem.getDataname(), article);
            }
        }
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

    // 部门网站
    @RequestMapping("department")
    public String department() {
        int departmentId = Integer.parseInt(request.getParameter("departmentid"));
        Department department = factorySession.get(Department.class, departmentId);
        request.setAttribute("department", department);
        String pagename = department.getTemplate();
        List<Dataitem> dataitems = factorySession.createCriteria(Dataitem.class)
                .add(Restrictions.eq("datamodel.id", department.getDatamodel().getId()))
                .list();
        for (Dataitem dataitem : dataitems) {
            Criteria criteriaArticle = factorySession.createCriteria(Article.class, "this_")
                    .createAlias("admin", "article_admin", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("article_admin.department",
                            "article_admin_department", JoinType.LEFT_OUTER_JOIN);
            criteriaArticle.add(Restrictions.eq("articleState.id", 4));
            criteriaArticle.add(Restrictions.eq("article_admin_department.id", departmentId));
            List<Integer> articleIds = new ArrayList<Integer>();
            articleIds.add(0);
            for (DataitemReColumns drc : dataitem.getDataitemReColumnses()) {
                for (ArticleReColumns arc : drc.getColumns().getArticleReColumnses())
                    if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                List<Columns> childs = factorySession.createCriteria(Columns.class)
                        .add(Restrictions.eq("parentId", drc.getColumns().getId())).list();
                for (Columns child : childs) {
                    for (ArticleReColumns arc : child.getArticleReColumnses())
                        if (!articleIds.contains(arc.getArticle().getId())) articleIds.add(arc.getArticle().getId());
                }
            }
            criteriaArticle.add(Restrictions.in("id", articleIds));
            if (dataitem.getDateastrict() > 0) criteriaArticle
                    .add(Restrictions.sqlRestriction("datediff(now(),publishtime)<?", dataitem.getDateastrict(),
                            StandardBasicTypes.INTEGER));
            if (dataitem.isHaveimage()) criteriaArticle.add(Restrictions.isNotNull("image"));
            Datasortfield datasortfield1 = dataitem.getDatasortfield1();
            Datasortfield datasortfield2 = dataitem.getDatasortfield2();
            Datasortfield datasortfield3 = dataitem.getDatasortfield3();
            Datasortmethod datasortmethod1 = dataitem.getDatasortmethod1();
            Datasortmethod datasortmethod2 = dataitem.getDatasortmethod2();
            Datasortmethod datasortmethod3 = dataitem.getDatasortmethod3();
            criteriaArticle.addOrder(datasortmethod1.equals("asc") ? Order.asc(datasortfield1.getField()) :
                    Order.desc(datasortfield1.getField())).addOrder(datasortmethod2.equals("asc") ?
                    Order.asc(datasortfield2.getField()) :
                    Order.desc(datasortfield2.getField())).addOrder(datasortmethod3.equals("asc") ?
                    Order.asc(datasortfield3.getField()) :
                    Order.desc(datasortfield3.getField()));
            int datacount = dataitem.getDatacount();
            if (datacount > 1) {
                List<Article> articles = criteriaArticle.setMaxResults(datacount).list();
                request.setAttribute(dataitem.getDataname(), articles);
            } else {
                Article article = (Article) criteriaArticle.setMaxResults(datacount).uniqueResult();
                request.setAttribute(dataitem.getDataname(), article);
            }
        }
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

    // 其它内容
    @RequestMapping("other")
    public String other() {
        int otherId = Integer.parseInt(request.getParameter("otherid"));
        Columns othercolumns = factorySession.get(Columns.class, otherId);
        request.setAttribute("other", othercolumns);
        String pagename = othercolumns.getTemplateother();
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

    // 大众留言
    @RequestMapping("leavemessage")
    public String leavemessage() {
        List<Leavemessage> leavemessages = factorySession.createCriteria(Leavemessage.class)
                .add(Restrictions.eq("checked", true))
                .addOrder(Order.desc("subtime")).list();
        request.setAttribute("leavemessages", leavemessages);
        String pagename = "leavemessage.html";
        frontpageCommon();
        request.setAttribute("viewcontentpath", webinfo.getTemplate() + "/" + pagename);
        return view();
    }

}
